<template>
  <div class="update-name">
    <van-nav-bar
      title="编辑昵称"
      left-text="取消"
      right-text="确定"
      @click-left="$emit('close')"
      @click-right="submitNewName"
    />

    <div class="field-wrap">
      <van-field
        v-model="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="7"
        placeholder="请输入新昵称"
        show-word-limit
      />
    </div>
    
  </div>
 
</template>
<script>
import { updateUserName } from '@/api/user'

export default {
  data() {
    return {
      localName: this.value
    }
  },
  props: ['value'],
  methods: {
    async submitNewName() {
      this.$toast.loading('修改昵称中...')

      try {
        if (this.localName.trim() === '') {
          return this.$toast('请输入昵称')
        }

        const {data} = updateUserName({
          name: this.localName
        })

        this.$emit('input', this.localName)
        this.$emit('close')
        this.$toast('更新成功')
      } catch(err) {
        console.log(err)
        if (err.response && err.response.status === 409) {
          return this.$toast('用户名已存在')
        }
        this.$toast('更新失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.update-name {
  .field-wrap {
    padding: 20px;
  }
}
</style>